<?php
/**
 * @author 刘国君
 * @version 1.0
 */

namespace app\Handel;

class SipContact{
    public $dispname;
    public $scheme = 'sip';
    public $username;
    public $password;
    public $domain; // 可包含 port
    public $parameters = array();

    function __construct($username='', $domain=''){
        $this->username = $username;
        $this->domain = $domain;
    }

    static function from_str($str){
        $ret = new SipContact();
        $ret->decode($str);
        return $ret;
    }

    function equals($dst){
        return ($this->username === $dst->username) && ($this->tag() == $dst->tag());
    }

    function address(){
        return "{$this->username}@{$this->domain}";
    }

    function set_tag($tag){
        $this->set_parameter('tag', $tag);
    }

    function del_tag(){
        $this->del_parameter('tag');
    }

    function tag(){
        return $this->get_parameter('tag');
    }

    function get_parameter($k){
        return $this->parameters[$k];
    }

    function set_parameter($k, $v){
        $this->parameters[$k] = $v;
    }
    function del_parameter($k){
        unset($this->parameters[$k]);
    }

    function encode(){
        $ret = '';
        if($this->dispname){
            $ret .= "\"{$this->dispname}\" ";
        }
        $ret .= "<{$this->scheme}:{$this->username}";
        if(strlen($this->password) > 0){
            $ret .= ":{$this->password}";
        }
        $ret .= "@{$this->domain}>";
        foreach($this->parameters as $k=>$v){
            $ret .= ";{$k}";
            if(strlen($v)){
                $ret .= "={$v}";
            }
        }
        return $ret;
    }

    function decode($str){
        $pos = strpos($str, '>');
        if($pos === false){
            $address = $str;
            $parameters = '';
        }else{
            $address = substr($str, 0, $pos + 1);
            $parameters = substr($str, $pos + 1);
        }

        $this->parse_address($address);

        $ps = explode(';', $parameters);
        foreach($ps as $p){
            $p = trim($p);
            if(strlen($p) == 0){
                continue;
            }
            $kv = explode('=', $p);
            $k = $kv[0];
            $v = isset($kv[1])? $kv[1] : '';
            $this->set_parameter($k, $v);
        }
    }
    private function parse_address($str){
        $pos = strpos($str, '<');
        if($pos!== false){
            $this->dispname = trim(substr($str, 0, $pos), '" ');
            $uri = substr($str, $pos);
        }else{
            $uri = $str;
        }
        $uri = trim($uri, '<>');

        $a = new SipUri();
        $a->decode($uri);
        $this->scheme = $a->scheme;
        $this->username = $a->username;
        $this->password = $a->password;
        $this->domain = $a->domain;
        return;
    }
}